package com.billdowney.util.request;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.billdowney.util.CommonUtil;

/**
 * @ClassName: RequestUtil
 * @Description: 客户端请求工具类
 * @author 超级小富翁 - BillDowney
 * @date 2018年4月13日 下午4:18:59
 */
public class RequestUtil {

	/**
	 * @Function: RequestUtil.java
	 * @Description: 获取真实IP地址
	 * @param request
	 *            客户端发送的请求
	 * @return 获取到的IP地址
	 * @author: 超级小富翁 - BillDowney
	 * @date: 2018年4月13日 下午4:20:22
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

	/**
	 * @Function: RequestUtil.java
	 * @Description: 获取当前请求的客户端类型
	 * @param request
	 *            客户端发送的请求
	 * @return 计算出的客户端类型
	 * @author: 超级小富翁 - BillDowney
	 * @date: 2018年4月13日 下午4:41:21
	 */
	public static String getClientType(HttpServletRequest request) {
		StringBuffer type = new StringBuffer("未在系统已有数据查询到该客户端类型");
		String userAgent = request.getHeader("user-agent");
		if(CommonUtil.isNotEmpty(userAgent)) {
			Set<String> keys = RequestUserAgentClientMap.userAgentMap.keySet();
			for (String key : keys) {
				if(userAgent.contains(key)) {
					return RequestUserAgentClientMap.userAgentMap.get(key);
				}
			}
		}
		return type.toString();
	}
}
